package com.kotlinvben.controller

import com.kotlinvben.bean.PageData
import com.kotlinvben.bean.Result
import com.kotlinvben.entity.Role
import com.kotlinvben.service.RoleService
import com.kotlinvben.utils.SecurityUtils
import com.kotlinvben.vo.RoleCreateVO
import com.kotlinvben.vo.RoleEnableVO
import com.kotlinvben.vo.RoleUpdateVO
import jakarta.validation.Valid
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort.Direction.ASC
import org.springframework.data.domain.Sort.by
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/system/role")
class RoleController(
    private val roleService: RoleService
) {
    @PostMapping
    fun createRole(@Valid @RequestBody roleCreateVO: RoleCreateVO): Result<Role> {
        val username = SecurityUtils.getCurrentUsername()
        val role = Role(
            name = roleCreateVO.name,
            code = roleCreateVO.code,
            status = roleCreateVO.status,
            remark = roleCreateVO.remark,
            createBy = username,
            modifyBy = username,
        )
        val createdRole = roleService.createRole(role, roleCreateVO.permissions)
        return Result.success(createdRole)
    }

    @PutMapping("/{id}")
    fun updateRole(
        @PathVariable id: Long,
        @Valid @RequestBody updateVO: RoleUpdateVO
    ): Result<Role> {
        return Result.success(roleService.updateRole(id, updateVO))
    }

    @DeleteMapping("/{id}")
    fun deleteRole(@PathVariable id: Long): Result<Unit> {
        roleService.deleteRole(id)
        return Result.success()
    }

    @GetMapping("/{id}")
    fun getRoleById(@PathVariable id: Long): Result<Role> {
        return Result.success(roleService.getRoleById(id))
    }

    @PutMapping("/{id}/disable")
    fun updateRoleDisable(
        @PathVariable id: Long,
        @RequestBody enableVO: RoleEnableVO
    ): Result<Unit> {
        roleService.updateRoleStatus(id, enableVO.status)
        return Result.success()
    }

    @GetMapping("/list")
    fun getRoles(
        @RequestParam(defaultValue = "0") page: Int,
        @RequestParam(defaultValue = "10") size: Int,
        @RequestParam(required = false) name: String?,
        @RequestParam(required = false) status: Int?
    ): Result<PageData<Role>> {
        val pageable = PageRequest.of(if (page > 0) page - 1 else page, size, by(ASC, "id"))
        val roles = roleService.getRoles(pageable, name, status)
        return Result.success(
            PageData.of(
                items = roles.content,
                total = roles.totalElements,
                page = page,
                size = size
            )
        )
    }

    @GetMapping("/assignable")
    fun getAssignableRoles(): Result<List<Role>> {
        return Result.success(roleService.getAssignableRoles())
    }
}